package com.esionet.common.utils;

import com.aliyun.oss.model.ObjectMetadata;
import com.esionet.common.exception.MyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;

import java.io.InputStream;


/**
 * Created by 陈熠
 * 2017/7/29.
 */
@Component
public class UploadUtil {
    @Value("${oss.accessKey}")
    private String ACCESS_KEY;
    @Value("${oss.secretKey}")
    private String SECRET_KEY;
    @Value("${oss.bucket}")
    private String BUCKET;
    @Value("${oss.endpoint}")
    private String ENDPOINT;
    @Value("${oss.domain}")
    private String DOMAIN;


    public String uploadFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new MyException("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();

        if (file.getSize() > 1 * 1024 * 1024) {
            throw new MyException("图片不能大于1M");
        }

        //上传文件
        String url = uploadImage(fileName, file.getInputStream());
        return url;
    }

    public  String uploadImage(String fileName, InputStream inputStream) {
        //获取oss
        String resultImgUrl = DOMAIN;
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        if (!ossClient.doesBucketExist(BUCKET)) {
            ossClient.createBucket(BUCKET);
        }
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentType("image/auto-orient,1/quality,q_90");
        try {
            //获取上传的图片文件名
            //获取扩展名
            String _extName = fileName.substring(fileName.indexOf("."));
            fileName = System.currentTimeMillis() +_extName ;
            ossClient.putObject(BUCKET, fileName, inputStream);
            ossClient.shutdown();
            resultImgUrl += fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("上传失败");
        } finally {
            ossClient.shutdown();
        }
        return resultImgUrl;
    }
}
